package controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.Domain;
import models.Keyword;
import server.PutCache;
import server.UpdateDomain;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

@SuppressWarnings("serial")
public class TopicServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		resp.setCharacterEncoding("utf-8");
		String path = ((HttpServletRequest)req).getRequestURI();
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 

        if(count != 2)
        {
        	try {
				req.getRequestDispatcher("/404error.jsp").forward(req, resp);
			} catch (Exception e) {
				e.printStackTrace();
			}
        	return;
        }
        
		// skip one token /question/abcd (remove sites)
		st.nextToken();
		String title_url = st.nextToken();
		
		if(title_url!=null)
		{
			if(title_url.equals("%E9%99%90%E5%88%B6%E7%B4%9A%E6%88%90%E4%BA%BA%E8%89%B2%E6%83%85%E5%9C%96%E7%89%87%E6%83%85%E8%89%B2av%E4%B8%8B%E8%BC%89%E5%8F%B0%E7%81%A3%E8%87%AA%E6%8B%8D%E5%81%B7%E6%8B%8D%E5%BD%B1%E7%89%87%E4%BA%BA%E5%A6%BB%E5%81%B7%E6%83%85%E6%97%A5%E8%A8%98&%20lt;%20BR%3E%E4%BA%BA%E5%A6%BB%E5%81%B7%E6%83%85%E6%96%87%E5%AD%B8%E6%88%90%E4%BA%BA%E6%BC%AB%E7%95%AB%E8%B2%BC%E5%9C%96%E7%AB%99"))
			{
				resp.sendError(resp.SC_NOT_FOUND,"Content removed because our policy !");
				return;
			}
			
			
			title_url = URLDecoder.decode(title_url,"UTF-8").trim();
			
			try {
				ObjectifyService.register(Keyword.class);
			} catch (Exception e) {
				// TODO: handle exception
			}
			Objectify objectify = ObjectifyService.begin();
			try {
				resp.setHeader( "Cache-Control", "public, max-age=86400");
				resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
//				
				Keyword domain = objectify.get(new Key<Keyword>(Keyword.class, title_url));
				
				req.setAttribute("keyword", domain);
			} catch (Exception e) {
				resp.sendRedirect("/gsearch?cx=009050056988840974278:fjfndh0x9ws&cof=FORID%3A10&ie=UTF-8&q="+title_url+"&sa=Search");
			}
			
			try {
				req.getRequestDispatcher("/topic.jsp").forward(req, resp);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			resp.sendRedirect("/gsearch?cx=009050056988840974278:fjfndh0x9ws&cof=FORID%3A10&ie=UTF-8&q="+title_url+"&sa=Search");
		}
	}
}
